package com.bsj.power.pls.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bsj.power.common.config.cached.BindCardCached;
import com.bsj.power.common.config.cached.PersonnelCached;
import com.bsj.power.common.config.cached.RedisCached;
import com.bsj.power.common.config.cached.WorkPersonnelCached;
import com.bsj.power.common.config.exception.ApiException;
import com.bsj.power.common.config.global.JsonResult;
import com.bsj.power.common.config.global.JsonResultEnum;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.constant.NumericalConstants;
import com.bsj.power.common.def.dto.DeleteDTO;
import com.bsj.power.common.def.dto.cardReport.BindCardDTO;
import com.bsj.power.common.def.dto.personnel.PersonnelDTO;
import com.bsj.power.common.def.dto.personnel.PersonnelSearchDTO;
import com.bsj.power.common.def.dto.personnel.WorkPersonnelSearchDTO;
import com.bsj.power.common.def.entity.job.JobPersonnel;
import com.bsj.power.common.def.entity.job.WorkPersonnel;
import com.bsj.power.common.def.entity.personGroup.PersonGroup;
import com.bsj.power.common.def.entity.personnel.Personnel;
import com.bsj.power.common.def.vo.KeyValueVO;
import com.bsj.power.common.def.vo.pls.PersonnelVO;
import com.bsj.power.common.def.vo.pls.WorkPersonnelVO;
import com.bsj.power.common.http.PersonHttp;
import com.bsj.power.common.mapper.*;
import com.bsj.power.common.util.DataUtil;
import com.bsj.power.common.util.ParamCheckUtil;
import com.bsj.power.pls.service.GroupService;
import com.bsj.power.pls.service.PersonnelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.bsj.power.common.util.DateUtils.getAgeByDate;

/**
 * @author LiJiaXin
 * @version 1.0.0
 * @description locationDeviceServiceImpl
 * @time 2024/4/18 17:08
 */
@Slf4j
@Service
public class PersonnelServiceImpl implements PersonnelService {

    @Resource
    private PersonnelMapper personnelMapper;

    @Resource
    private GroupMapper groupMapper;

    @Autowired
    private PersonnelCached personnelCached;

    @Autowired
    private BindCardCached bindCardCached;

    @Autowired
    private GroupService groupService;

    @Resource
    private JobPersonnelMapper jobPersonnelMapper;

    @Resource
    private WorkPersonnelMapper workPersonnelMapper;

    @Resource
    private PersonGroupMapper personGroupMapper;

    @Autowired
    private RedisCached redisCached;

    @Autowired
    private WorkPersonnelCached workPersonnelCached;

    @Autowired
    private PersonHttp personHttp;

    /**
     * 添加人员信息
     *
     * @param personnelDTO
     * @return com.bsj.power.common.config.global.JsonResult
     * @author ljx
     * @time 2024/4/18 17:12
     */
    @Override
    @Transactional
    public JsonResult addPersonnel(PersonnelDTO personnelDTO) {
        paramCheck(personnelDTO);
        Personnel personnel = new Personnel();
        BeanUtils.copyProperties(personnelDTO, personnel);
        if (personnelMapper.insert(personnel) > NumericalConstants.ZERO) {
            personnelCached.hsetPersonnelInfo(personnel);
            return JsonResult.success();
        } else {
            return JsonResult.fail();
        }
    }

    /**
     * 删除人员
     *
     * @param deleteDTO
     * @return com.bsj.power.common.config.global.JsonResult
     * @author ljx
     * @time 2024/4/18 20:01
     */
    @Override
    @Transactional
    public JsonResult deletePersonnel(DeleteDTO deleteDTO) {
        Integer[] personnelIds = deleteDTO.getPersonnelIds();
        if (personnelIds == null || personnelIds.length == NumericalConstants.ZERO) {
            return JsonResult.fail(JsonResultEnum.PARAM_ERROR);
        }
        List<Integer> ids = Arrays.stream(personnelIds).collect(Collectors.toList());
        List<Personnel> personnelList = personnelMapper.selectList(Wrappers.<Personnel>lambdaQuery().in(Personnel::getPersonnelId, ids));
        ParamCheckUtil.isEmpty(personnelList, JsonResultEnum.PERSONNEL_NOT_EXIST);
        String empNo;
        List<String> empNos = new LinkedList<>();
        for (Personnel personnel : personnelList) {
            //正在绑卡状态中的人员无法删除
            empNo = personnel.getEmpNo();
            empNos.add(empNo);
            if (bindCardCached.hgetBindCardInfo(RedisConstant.BIND_CARD_REDIS_EMP_NO_KEY + empNo) != null) {
                return JsonResult.fail(personnel.getName() + JsonResultEnum.PERSONNEL_BIND_CARD.getMsg());
            }
        }
        if (personnelMapper.deleteBatchIds(ids) > NumericalConstants.ZERO) {
            jobPersonnelMapper.delete(Wrappers.<JobPersonnel>lambdaQuery().in(JobPersonnel::getPersonnelId, ids));
            for (String str : empNos) {
                personnelCached.hdelPersonnelInfo(str);
            }
            return JsonResult.success();
        } else {
            return JsonResult.fail();
        }
    }

    /**
     * 修改人员信息
     *
     * @param personnelDTO
     * @return com.bsj.power.common.config.global.JsonResult
     * @author ljx
     * @time 2024/4/18 17:37
     */
    @Override
    @Transactional
    public JsonResult updatePersonnel(PersonnelDTO personnelDTO) {
        Integer personnelId = personnelDTO.getPersonnelId();
        ParamCheckUtil.isNull(personnelId);
        Personnel oldPersonnel = personnelMapper.selectById(personnelId);
        ParamCheckUtil.isNull(oldPersonnel, JsonResultEnum.PERSONNEL_NOT_EXIST);
        String empNo = personnelDTO.getEmpNo();
        if (!oldPersonnel.getEmpNo().equals(empNo)) {
            return JsonResult.fail(JsonResultEnum.EMP_NO_CANNOT_UPDATE);
        }
        paramCheck(personnelDTO);
        Personnel personnel = new Personnel();
        BeanUtils.copyProperties(personnelDTO, personnel);
        if (personnelMapper.updateById(personnel) > NumericalConstants.ZERO) {
//            String oldIdCardNo = oldPersonnel.getIdCardNo();
            String idCardNo = personnel.getIdCardNo();
//            String extEventPersonNo = null;
//            if (StringUtils.isNotBlank(idCardNo) && StringUtils.isNotBlank(oldIdCardNo) && !idCardNo.equals(oldIdCardNo)) {
//                extEventPersonNo = personHttp.getExtEventPersonNoByIdCardNo(idCardNo);
//                if (StringUtils.isNotBlank(extEventPersonNo)) {
//                    personnelMapper.updateById(new Personnel(personnelId, extEventPersonNo));
//                }
//            }
            BindCardDTO bindCardDTO = bindCardCached.hgetBindCardInfo(RedisConstant.BIND_CARD_REDIS_EMP_NO_KEY + empNo);
            //防止绑卡后修改作业人员导致退卡时人员信息校验不通过
            if (bindCardDTO != null) {
                bindCardDTO.setPersonnelName(personnelDTO.getName());
                bindCardDTO.setPhone(personnel.getPhone());
                bindCardDTO.setIdCardNo(idCardNo);
                //身份证修改表示需要修改绑卡信息、安防平台人员编号等缓存
//                if (StringUtils.isNotBlank(extEventPersonNo)) {
//                    //旧人员编号
//                    String oldExtEventPersonNo = bindCardDTO.getExtEventPersonNo();
//                    if (StringUtils.isNotBlank(oldExtEventPersonNo)) {
//                        //删除旧的安防平台人员编号缓存
//                        redisCached.del(RedisConstant.EXT_EVENT_PERSON_NO_KEY + oldExtEventPersonNo);
//                    }
//                    //添加新的安防平台人员编号缓存
//                    redisCached.set(RedisConstant.EXT_EVENT_PERSON_NO_KEY + extEventPersonNo, extEventPersonNo);
//                    bindCardDTO.setExtEventPersonNo(extEventPersonNo);
//                }
                bindCardCached.hsetBindCardInfo(bindCardDTO);
            }
            personnelCached.hsetPersonnelInfo(personnel);
            return JsonResult.success();
        } else {
            return JsonResult.fail();
        }
    }

    /**
     * 获取单个人员信息
     *
     * @param personnelId
     * @return com.bsj.power.common.def.vo.pls.PersonnelVO
     * @author ljx
     * @time 2024/4/18 20:01
     */
    @Override
    public PersonnelVO getPersonnelById(Integer personnelId) {
        ParamCheckUtil.isNull(personnelId);
        Personnel personnel = personnelMapper.selectById(personnelId);
        ParamCheckUtil.isNull(personnel, JsonResultEnum.PERSONNEL_NOT_EXIST);
        PersonnelVO personnelVO = new PersonnelVO();
        BeanUtils.copyProperties(personnel, personnelVO);
        return personnelVO;
    }

    /**
     * 人员分页
     *
     * @param personnelSearchDTO
     * @return com.bsj.power.common.config.global.JsonResult<java.util.List < com.bsj.power.common.def.vo.pls.PersonnelVO>>
     * @author ljx
     * @time 2024/4/18 20:02
     */
    @Override
    public JsonResult<List<PersonnelVO>> pagePersonnel(PersonnelSearchDTO personnelSearchDTO) {
        QueryWrapper<Personnel> queryWrapper = new QueryWrapper<>();
        String name = personnelSearchDTO.getName();
        String empNo = personnelSearchDTO.getEmpNo();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(empNo)) {
            queryWrapper.eq("emp_no", empNo);
        }
        Integer isAttention = personnelSearchDTO.getIsAttention();
        if (isAttention != null) {
            queryWrapper.eq("is_attention", isAttention);
        }
        long total = NumericalConstants.ZERO;
        List<PersonnelVO> personnelVOS = new LinkedList<>();
        List<Personnel> personnelList = personnelMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(personnelList)) {
            return JsonResult.success(personnelVOS, total);
        }
        Boolean isBind = personnelSearchDTO.getIsBind();
        if (isBind != null) {
            if (isBind) {
                personnelList = personnelList.stream().filter(personnel -> bindCardCached.hgetBindCardInfo(RedisConstant.BIND_CARD_REDIS_EMP_NO_KEY + personnel.getEmpNo()) != null).collect(Collectors.toList());
            } else {
                personnelList = personnelList.stream().filter(personnel -> bindCardCached.hgetBindCardInfo(RedisConstant.BIND_CARD_REDIS_EMP_NO_KEY + personnel.getEmpNo()) == null).collect(Collectors.toList());
            }
        }
        if (CollectionUtils.isEmpty(personnelList)) {
            return JsonResult.success(personnelVOS, total);
        }
        total = personnelList.size();
        personnelList = DataUtil.pagingByList(personnelList, personnelSearchDTO.getPageSize(), personnelSearchDTO.getPageNumber());
        List<Integer> groupIds = personnelList.stream().map(Personnel::getGroupId).collect(Collectors.toList());
        Map<Integer, PersonGroup> personGroupMap = null;
        if (!CollectionUtils.isEmpty(groupIds)) {
            List<PersonGroup> personGroups = personGroupMapper.selectList(Wrappers.<PersonGroup>lambdaQuery()
                    .in(PersonGroup::getGroupId, groupIds).eq(PersonGroup::getGroupType, NumericalConstants.TWO));
            if (!CollectionUtils.isEmpty(personGroups)) {
                personGroupMap = personGroups.stream().collect(Collectors.toMap(PersonGroup::getGroupId, Function.identity()));
            }
        }
        for (Personnel personnel : personnelList) {
            PersonnelVO personnelVO = new PersonnelVO();
            BeanUtils.copyProperties(personnel, personnelVO);
            BindCardDTO bindCardDTO = bindCardCached.hgetBindCardInfo(RedisConstant.BIND_CARD_REDIS_EMP_NO_KEY + personnel.getEmpNo());
            if (bindCardDTO != null) {
                personnelVO.setSn(bindCardDTO.getDeviceName());
            }
            if (!CollectionUtils.isEmpty(personGroupMap)) {
                PersonGroup personGroup = personGroupMap.get(personnel.getGroupId());
                if (personGroup != null) {
                    personnelVO.setGroupName(personGroup.getGroupName());
                }
            }
            String dateOfBirth = personnel.getDateOfBirth();
            if (StringUtils.isNotBlank(dateOfBirth)) {
                personnelVO.setAge(getAgeByDate(dateOfBirth));
            }
            personnelVO.setCreateTime(DateUtil.formatDateTime(personnel.getCreateTime()));
            personnelVO.setUpdateTime(DateUtil.formatDateTime(personnel.getUpdateTime()));
            personnelVO.setStatus(personnel.getStatus().equals("ACTIVE") ? "活动" : "不活动");
            personnelVOS.add(personnelVO);
        }
        return JsonResult.success(personnelVOS, total);
    }

    /**
     * 作业人员信息
     *
     * @param dto
     * @return
     */
    @Override
    public JsonResult<List<WorkPersonnelVO>> pageWorkPersonnel(WorkPersonnelSearchDTO dto) {
//        IPage<WorkPersonnel> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        QueryWrapper<WorkPersonnel> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getName())) {
            queryWrapper.lambda().like(WorkPersonnel::getName, dto.getName());
        }
        Integer groupId = dto.getGroupId();
        if (groupId != null) {
            queryWrapper.lambda().eq(WorkPersonnel::getGroupId, groupId);
        }
        Integer isAttention = dto.getIsAttention();
        if (isAttention != null) {
            queryWrapper.lambda().eq(WorkPersonnel::getIsAttention, isAttention);
        }
        queryWrapper.lambda().orderByDesc(WorkPersonnel::getCreateTime);
        long total = NumericalConstants.ZERO;
        List<WorkPersonnelVO> workPersonnelVOS = new ArrayList<>();
        List<WorkPersonnel> workPersonnelList = workPersonnelMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(workPersonnelList)) {
            return JsonResult.success(workPersonnelVOS, total);
        }
        Boolean isBind = dto.getIsBind();
        if (isBind != null) {
            if (isBind) {
                workPersonnelList = workPersonnelList.stream().filter(workPersonnel -> bindCardCached.hgetBindCardInfo(RedisConstant.BIND_CARD_REDIS_EMP_NO_KEY + workPersonnel.getTemporaryEmpNo()) != null).collect(Collectors.toList());
            } else {
                workPersonnelList = workPersonnelList.stream().filter(workPersonnel -> bindCardCached.hgetBindCardInfo(RedisConstant.BIND_CARD_REDIS_EMP_NO_KEY + workPersonnel.getTemporaryEmpNo()) == null).collect(Collectors.toList());
            }
        }
        if (CollectionUtils.isEmpty(workPersonnelList)) {
            return JsonResult.success(workPersonnelVOS, total);
        }
        total = workPersonnelList.size();
        workPersonnelList = DataUtil.pagingByList(workPersonnelList, dto.getPageSize(), dto.getPageNumber());

        List<Integer> groupIds = workPersonnelList.stream().map(WorkPersonnel::getGroupId).collect(Collectors.toList());
        Map<Integer, PersonGroup> personGroupMap = null;
        if (!CollectionUtils.isEmpty(groupIds)) {
            List<PersonGroup> personGroups = personGroupMapper.selectList(Wrappers.<PersonGroup>lambdaQuery()
                    .in(PersonGroup::getGroupId, groupIds).eq(PersonGroup::getGroupType, NumericalConstants.TWO));
            if (!CollectionUtils.isEmpty(personGroups)) {
                personGroupMap = personGroups.stream().collect(Collectors.toMap(PersonGroup::getGroupId, Function.identity()));
            }
        }
        for (WorkPersonnel item : workPersonnelList) {
            WorkPersonnelVO workPersonnelVO = new WorkPersonnelVO();
            BeanUtils.copyProperties(item, workPersonnelVO);
            BindCardDTO bindCardDTO = bindCardCached.hgetBindCardInfo(RedisConstant.BIND_CARD_REDIS_EMP_NO_KEY + item.getTemporaryEmpNo());
            if (bindCardDTO != null) {
                workPersonnelVO.setSn(bindCardDTO.getDeviceName());
            }
            if (!CollectionUtils.isEmpty(personGroupMap)) {
                PersonGroup personGroup = personGroupMap.get(item.getGroupId());
                if (personGroup != null) {
                    workPersonnelVO.setGroupName(personGroup.getGroupName());
                }
            }
            workPersonnelVO.setAge(LocationDeviceServiceImpl.getAgeByIdCodeNo(item.getIdCardNo()));
            workPersonnelVOS.add(workPersonnelVO);
        }

        return JsonResult.success(workPersonnelVOS, total);
    }

    /**
     * 模糊搜索
     *
     * @param value
     * @param isBind
     * @return java.util.List<com.bsj.power.common.def.vo.KeyValueVO>
     * @author ljx
     * @time 2024/5/10 14:10
     */
    @Override
    public List<KeyValueVO> fuzzySearch(String value, Boolean isBind) {
        List<KeyValueVO> keyValueVOS = new LinkedList<>();
        if (StringUtils.isBlank(value)) {
            return keyValueVOS;
        }
        List<Personnel> personnelList = personnelCached.hgetAllPersonnelInfo();
        if (CollectionUtils.isEmpty(personnelList)) {
            return keyValueVOS;
        }
        value = DataUtil.escape(value);
        List<String> empNoList = new LinkedList<>();
        for (Personnel personnel : personnelList) {
            String empNo = personnel.getEmpNo();
            if (isBind != null && !isBind) {
                BindCardDTO bindCardDTO = bindCardCached.hgetBindCardInfo(RedisConstant.BIND_CARD_REDIS_EMP_NO_KEY + empNo);
                if (bindCardDTO != null) {
                    continue;
                }
            }
            empNoList.add(empNo);
        }

        List<KeyValueVO> personnelNames = personnelMapper.fuzzySearch(value, NumericalConstants.ONE, empNoList);
        List<KeyValueVO> empNos = personnelMapper.fuzzySearch(value, NumericalConstants.TWO, empNoList);
        keyValueVOS.addAll(personnelNames.stream().map(keyValueVO -> {
            keyValueVO.setType(NumericalConstants.ONE);
            return keyValueVO;
        }).collect(Collectors.toList()));
        keyValueVOS.addAll(empNos.stream().map(keyValueVO -> {
            keyValueVO.setType(NumericalConstants.TWO);
            return keyValueVO;
        }).collect(Collectors.toList()));

        return keyValueVOS;
    }

//    /**
//     * 人员信息同步
//     *
//     * @return com.bsj.power.common.config.global.JsonResult
//     * @author ljx
//     * @time 2024/7/10 10:20
//     */
//    @Override
//    @Transactional
//    public JsonResult personnelInfoSync() {
//        String str = HttpUtil.get(ApiConstants.PAGE_GET_PERSONNEL + "&personid=");
//        if (StringUtils.isNotBlank(str)) {
//            JSONObject data = JSON.parseObject(str);
//            Integer status = data.getInteger("status");
//            if (status != null && status.equals(JsonResultEnum.SUCCESS.getCode())) {
//                JSONArray jsonArray = data.getJSONArray("result");
//                if (!CollectionUtils.isEmpty(jsonArray)) {
//                    List<HttpPersonnelVO> httpPersonnelVOS = jsonArray.toJavaList(HttpPersonnelVO.class);
//                    if (!CollectionUtils.isEmpty(httpPersonnelVOS)) {
//                        List<Personnel> personnelList = httpPersonnelVOS.stream().map(httpPersonnelVO -> {
//                            Personnel personnel = new Personnel(httpPersonnelVO);
//                            String sex = httpPersonnelVO.getN_sex();
//                            String nAge = httpPersonnelVO.getN_age();
//                            String nPost = httpPersonnelVO.getN_post();
//                            if (StringUtils.isNotBlank(sex)) {
//                                personnel.setGender(sex.equals("男") ? NumericalConstants.ONE : NumericalConstants.TWO);
//                            }
//                            personnel.setAge(StringUtils.isNotBlank(nAge) ? Integer.parseInt(nAge) : null);
//                            if (StringUtils.isNotBlank(nPost)) {
//                                personnel.setType(postToType(nPost));
//                            }
//                            return personnel;
//                        }).collect(Collectors.toList());
//                        personnelMapper.batchAdd(personnelList);
//                        personnelList.forEach(personnel -> {
//                            personnelCached.hsetPersonnelInfo(personnel);
//                        });
//                    }
//                }
//            }
//        }
//        return null;
//    }

    /**
     * 根据id获取作业人员信息
     *
     * @param id
     * @return com.bsj.power.common.def.vo.pls.WorkPersonnelVO
     * @author ljx
     * @time 2024/9/12 14:36
     */
    @Override
    public WorkPersonnelVO getWorkPersonnelById(Integer id) {
        ParamCheckUtil.isNull(id);
        WorkPersonnel workPersonnel = workPersonnelMapper.selectById(id);
        ParamCheckUtil.isNull(workPersonnel, JsonResultEnum.PERSONNEL_NOT_EXIST);
        WorkPersonnelVO workPersonnelVO = new WorkPersonnelVO();
        BeanUtils.copyProperties(workPersonnel, workPersonnelVO);
        workPersonnelVO.setAge(LocationDeviceServiceImpl.getAgeByIdCodeNo(workPersonnel.getIdCardNo()));
        Integer groupId = workPersonnel.getGroupId();
        if (groupId != null) {
            PersonGroup personGroup = personGroupMapper.selectById(groupId);
            if (personGroup != null) {
                workPersonnelVO.setGroupName(personGroup.getGroupName());
            }
        }
        return workPersonnelVO;
    }

    /**
     * 是否关注
     *
     * @param personType  人员类型 1负责人 2作业人员
     * @param personId    人员id
     * @param isAttention 1关注 2取消关注
     * @return com.bsj.power.common.config.global.JsonResult
     * @author ljx
     * @time 2024/9/25 19:39
     */
    @Override
    @Transactional
    public JsonResult isAttention(Integer personType, Integer personId, Integer isAttention) {
        if (personType == null || personId == null || isAttention == null) {
            return JsonResult.fail(JsonResultEnum.PARAM_ERROR);
        }
        if (!personType.equals(NumericalConstants.ONE) && !personType.equals(NumericalConstants.TWO)) {
            return JsonResult.fail(JsonResultEnum.PARAM_ERROR);
        }
        if (!isAttention.equals(NumericalConstants.ONE) && !isAttention.equals(NumericalConstants.TWO)) {
            return JsonResult.fail(JsonResultEnum.PARAM_ERROR);
        }
        if (personType.equals(NumericalConstants.ONE)) {
            Personnel personnel = personnelMapper.selectById(personId);
            ParamCheckUtil.isNull(personnel, JsonResultEnum.PERSONNEL_NOT_EXIST);
            personnel.setIsAttention(isAttention);
            personnelMapper.updateById(personnel);
            personnelCached.hsetPersonnelInfo(personnel);
        } else {
            WorkPersonnel workPersonnel = workPersonnelMapper.selectById(personId);
            ParamCheckUtil.isNull(workPersonnel, JsonResultEnum.PERSONNEL_NOT_EXIST);
            workPersonnel.setIsAttention(isAttention);
            workPersonnelMapper.updateById(workPersonnel);
            workPersonnelCached.setWorkPersonnelInfo(workPersonnel);
        }
        return JsonResult.success();
    }

    /**
     * 负责人员关注人员列表
     *
     * @return java.util.List<com.bsj.power.common.def.entity.personnel.Personnel>
     * @author ljx
     * @time 2024/9/25 20:14
     */
    @Override
    public List<Personnel> attentionPersonnelList() {
        return personnelMapper.selectList(Wrappers.<Personnel>lambdaQuery().eq(Personnel::getIsAttention, NumericalConstants.ONE));
    }

    /**
     * 作业人员关注人员列表
     *
     * @return java.util.List<com.bsj.power.common.def.entity.job.WorkPersonnel>
     * @author ljx
     * @time 2024/9/25 20:15
     */
    @Override
    public List<WorkPersonnel> attentionWorkPersonnelList() {
        return workPersonnelMapper.selectList(Wrappers.<WorkPersonnel>lambdaQuery().eq(WorkPersonnel::getIsAttention, NumericalConstants.ONE));
    }

    /**
     * 删除作业人员信息
     *
     * @param deleteDTO
     * @return com.bsj.power.common.config.global.JsonResult
     * @author ljx
     * @time 2024/11/19 16:23
     */
    @Override
    public JsonResult deleteWorkPersonnel(DeleteDTO deleteDTO) {
        Integer[] personnelIds = deleteDTO.getPersonnelIds();
        if (personnelIds == null || personnelIds.length == NumericalConstants.ZERO) {
            return JsonResult.fail(JsonResultEnum.PARAM_ERROR);
        }
        List<Integer> ids = Arrays.stream(personnelIds).collect(Collectors.toList());
        List<WorkPersonnel> workPersonnelList = workPersonnelMapper.selectList(Wrappers.<WorkPersonnel>lambdaQuery().in(WorkPersonnel::getWorkPersonnelId, ids));
        ParamCheckUtil.isEmpty(workPersonnelList, JsonResultEnum.PERSONNEL_NOT_EXIST);
        String temporaryEmpNo;
        List<String> temporaryEmpNos = new LinkedList<>();
        for (WorkPersonnel workPersonnel : workPersonnelList) {
            //正在绑卡状态中的人员无法删除
            temporaryEmpNo = workPersonnel.getTemporaryEmpNo();
            temporaryEmpNos.add(temporaryEmpNo);
            if (bindCardCached.hgetBindCardInfo(RedisConstant.BIND_CARD_REDIS_EMP_NO_KEY + temporaryEmpNo) != null) {
                return JsonResult.fail(workPersonnel.getName() + JsonResultEnum.PERSONNEL_BIND_CARD.getMsg());
            }
        }
        int count = workPersonnelMapper.deleteBatchIds(ids);
        if (count > NumericalConstants.ZERO) {
            //删除作业人员与工单的关联关系
            jobPersonnelMapper.delete(Wrappers.<JobPersonnel>lambdaQuery().in(JobPersonnel::getPersonnelId, ids));
            for (String str : temporaryEmpNos) {
                workPersonnelCached.delWorkPersonnelInfo(str);
            }
            return JsonResult.success();
        } else {
            return JsonResult.fail();
        }
    }

    @Override
    public Map<String, String> getPersonNoInfo() {
        Map<String, String> map = new HashMap<>();
        List<BindCardDTO> bindCardDTOS = bindCardCached.hgetAllBindCard();
        redisCached.set(RedisConstant.EXT_EVENT_PERSON_NO_KEY + "4234bc5816734eb68ede6a9fd819eb50", "4234bc5816734eb68ede6a9fd819eb50");
        if (!CollectionUtils.isEmpty(bindCardDTOS)) {
            //已绑卡人员的编号
            List<String> list = bindCardDTOS.stream().map(BindCardDTO::getExtEventPersonNo).filter(s -> StringUtils.isNotBlank(s)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(list)) {
                //未绑卡且人员编号不为空的负责人
                List<Personnel> personnelList = personnelMapper.selectList(Wrappers.<Personnel>lambdaQuery().notIn(Personnel::getExtEventPersonNo, list).isNotNull(Personnel::getExtEventPersonNo));
                if (!CollectionUtils.isEmpty(personnelList)) {
                    personnelList.forEach(personnel -> {
                        String extEventPersonNo = personnel.getExtEventPersonNo();
                        String s = redisCached.get(RedisConstant.EXT_EVENT_PERSON_NO_KEY + extEventPersonNo);
                        if (StringUtils.isNotBlank(s)) {
                            //脏数据
                            map.put(extEventPersonNo, personnel.getName());
                        }
                    });

                }

                //未绑卡且人员编号不为空的作业人员
                List<WorkPersonnel> workPersonnelList = workPersonnelMapper.selectList(Wrappers.<WorkPersonnel>lambdaQuery().notIn(WorkPersonnel::getExtEventPersonNo, list).isNotNull(WorkPersonnel::getExtEventPersonNo));
                if (!CollectionUtils.isEmpty(workPersonnelList)) {
                    workPersonnelList.forEach(workPersonnel -> {
                        String extEventPersonNo = workPersonnel.getExtEventPersonNo();
                        String s = redisCached.get(RedisConstant.EXT_EVENT_PERSON_NO_KEY + extEventPersonNo);
                        if (StringUtils.isNotBlank(s)) {
                            //脏数据
                            map.put(extEventPersonNo, workPersonnel.getName());
                        }
                    });

                }
            } else {
                //未绑卡且人员编号不为空的负责人
                List<Personnel> personnelList = personnelMapper.selectList(Wrappers.<Personnel>lambdaQuery().isNotNull(Personnel::getExtEventPersonNo));
                if (!CollectionUtils.isEmpty(personnelList)) {
                    personnelList.forEach(personnel -> {
                        String extEventPersonNo = personnel.getExtEventPersonNo();
                        String s = redisCached.get(RedisConstant.EXT_EVENT_PERSON_NO_KEY + extEventPersonNo);
                        if (StringUtils.isNotBlank(s)) {
                            //脏数据
                            map.put(extEventPersonNo, personnel.getName());
                        }
                    });

                }

                //未绑卡且人员编号不为空的作业人员
                List<WorkPersonnel> workPersonnelList = workPersonnelMapper.selectList(Wrappers.<WorkPersonnel>lambdaQuery().isNotNull(WorkPersonnel::getExtEventPersonNo));
                if (!CollectionUtils.isEmpty(workPersonnelList)) {
                    workPersonnelList.forEach(workPersonnel -> {
                        String extEventPersonNo = workPersonnel.getExtEventPersonNo();
                        String s = redisCached.get(RedisConstant.EXT_EVENT_PERSON_NO_KEY + extEventPersonNo);
                        if (StringUtils.isNotBlank(s)) {
                            //脏数据
                            map.put(extEventPersonNo, workPersonnel.getName());
                        }
                    });

                }
            }
        }
        return map;
    }

    @Override
    public Map<String, String> cleanPersonNoInfo() {
        Map<String, String> map = new HashMap<>();
        List<BindCardDTO> bindCardDTOS = bindCardCached.hgetAllBindCard();
        if (!CollectionUtils.isEmpty(bindCardDTOS)) {
            //已绑卡人员的编号
            List<String> list = bindCardDTOS.stream().map(BindCardDTO::getExtEventPersonNo).filter(s -> StringUtils.isNotBlank(s)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(list)) {
                //未绑卡且人员编号不为空的负责人
                List<Personnel> personnelList = personnelMapper.selectList(Wrappers.<Personnel>lambdaQuery().notIn(Personnel::getExtEventPersonNo, list).isNotNull(Personnel::getExtEventPersonNo));
                if (!CollectionUtils.isEmpty(personnelList)) {
                    personnelList.forEach(personnel -> {
                        String extEventPersonNo = personnel.getExtEventPersonNo();
                        boolean flag = redisCached.del(RedisConstant.EXT_EVENT_PERSON_NO_KEY + extEventPersonNo);
                        if (flag) {
                            //删除掉的脏数据
                            map.put(extEventPersonNo, personnel.getName());
                        }
                    });

                }

                //未绑卡且人员编号不为空的作业人员
                List<WorkPersonnel> workPersonnelList = workPersonnelMapper.selectList(Wrappers.<WorkPersonnel>lambdaQuery().notIn(WorkPersonnel::getExtEventPersonNo, list).isNotNull(WorkPersonnel::getExtEventPersonNo));
                if (!CollectionUtils.isEmpty(workPersonnelList)) {
                    workPersonnelList.forEach(workPersonnel -> {
                        String extEventPersonNo = workPersonnel.getExtEventPersonNo();
                        boolean flag = redisCached.del(RedisConstant.EXT_EVENT_PERSON_NO_KEY + extEventPersonNo);
                        if (flag) {
                            //删除掉的脏数据
                            map.put(extEventPersonNo, workPersonnel.getName());
                        }
                    });

                }
            } else {
                //未绑卡且人员编号不为空的负责人
                List<Personnel> personnelList = personnelMapper.selectList(Wrappers.<Personnel>lambdaQuery().isNotNull(Personnel::getExtEventPersonNo));
                if (!CollectionUtils.isEmpty(personnelList)) {
                    personnelList.forEach(personnel -> {
                        String extEventPersonNo = personnel.getExtEventPersonNo();
                        boolean flag = redisCached.del(RedisConstant.EXT_EVENT_PERSON_NO_KEY + extEventPersonNo);
                        if (flag) {
                            //删除掉的脏数据
                            map.put(extEventPersonNo, personnel.getName());
                        }
                    });

                }

                //未绑卡且人员编号不为空的作业人员
                List<WorkPersonnel> workPersonnelList = workPersonnelMapper.selectList(Wrappers.<WorkPersonnel>lambdaQuery().isNotNull(WorkPersonnel::getExtEventPersonNo));
                if (!CollectionUtils.isEmpty(workPersonnelList)) {
                    workPersonnelList.forEach(workPersonnel -> {
                        String extEventPersonNo = workPersonnel.getExtEventPersonNo();
                        boolean flag = redisCached.del(RedisConstant.EXT_EVENT_PERSON_NO_KEY + extEventPersonNo);
                        if (flag) {
                            //删除掉的脏数据
                            map.put(extEventPersonNo, workPersonnel.getName());
                        }
                    });

                }
            }
        }
        return map;
    }

    /**
     * 岗位转类型
     *
     * @param nPost
     * @return void
     * @author ljx
     * @time 2024/7/10 14:01
     */
    private static Integer postToType(String nPost) {
        Integer type;
        switch (nPost) {
            case "管理人员":
                type = NumericalConstants.ONE;
                break;
            case "安全巡视人员":
                type = NumericalConstants.TWO;
                break;
            case "运行人员":
                type = NumericalConstants.THREE;
                break;
            case "维修人员":
                type = NumericalConstants.FOUR;
                break;
            case "其他人员":
            default:
                type = NumericalConstants.FIVE;
                break;
        }
        return type;
    }

    /**
     * 参数校验
     *
     * @param personnelDTO
     * @return void
     * @author ljx
     * @time 2024/4/18 17:26
     */
    private void paramCheck(PersonnelDTO personnelDTO) {
        String phone = personnelDTO.getPhone();
        //手机号校验
        if (StringUtils.isNotBlank(phone) && !Validator.isMobile(phone)) {
            throw new ApiException(JsonResultEnum.PHONE_FORMAT_ERROR);
        }
//        ParamCheckUtil.isNull(groupMapper.selectById(personnelDTO.getGroupId()), JsonResultEnum.GROUP_NOT_EXIST);
        Integer personnelId = personnelDTO.getPersonnelId();
        String idCardNo = personnelDTO.getIdCardNo();
        //去重校验
        if (StringUtils.isNotBlank(idCardNo)) {
            if (!Validator.isCitizenId(idCardNo)) {
                throw new ApiException(JsonResultEnum.ID_CARD_NO_FORMAT_ERROR);
            }
            if (personnelMapper.checkIsExist(idCardNo, personnelId) > NumericalConstants.ZERO) {
                throw new ApiException(JsonResultEnum.ID_CARD_NO_EXIST);
            }
        }
        QueryWrapper<Personnel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("emp_no", personnelDTO.getEmpNo());
        if (personnelId != null) {
            queryWrapper.ne("personnel_id", personnelId);
        }
        if (personnelMapper.exists(queryWrapper)) {
            throw new ApiException(JsonResultEnum.EMP_NO_EXIST);
        }
    }

//    /**
//     * 检查是否存在
//     *
//     * @param column
//     * @param value
//     * @param personnelId
//     * @param jsonResultEnum
//     * @return void
//     * @author ljx
//     * @time 2024/4/19 10:32
//     */
//    private void checkIsExist(String column, String value, Integer personnelId, JsonResultEnum jsonResultEnum) {
//        QueryWrapper<Personnel> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq(column, value);
//        if (personnelId != null) {
//            queryWrapper.ne("personnel_id", personnelId);
//        }
//        if (personnelMapper.exists(queryWrapper)) {
//            throw new ApiException(jsonResultEnum);
//        }
//    }
}
